<script setup>
import request from "@/utils/request";
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";

const formRef = ref()
const data = reactive({
  form: {},
  src: '',
  rules: {
    telephone: [
      {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
    ],
  },
  fileList: [] // 用于存储当前上传队列的文件列表
})

data.form = JSON.parse(localStorage.getItem("xm-pro-employee"))
data.src = data.form.avatar
console.log(data.form)


const update = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      data.form.avatar = data.src
      request.put("/employee", data.form).then(res => {
        console.log(data.form)
        if (res.code === '0') {
          ElMessage.success("保存成功")
          localStorage.setItem("xm-pro-employee", JSON.stringify(data.form))
          setTimeout(() => {
            window.location.reload();
          }, 500)
        } else {
          ElMessage.error("保存失败")
        }
      })
    }
  })
  data.fileList = [];
}

const filesUploadSuccess = (res) => {
  data.src = res.data
}
</script>

<template>
  <div>
    <el-card style="width: 40%; margin: 10px">
      <el-form ref="formRef" :model="data.form" :rules="data.rules"  label-width="80px">
        <el-form-item label="头像">
          <template #default="scope">
            <el-image style="width: 50px; height: 50px" :src="data.src"
                      :preview-src-list="[data.src]"
                      preview-teleported="true"/>
          </template>
        </el-form-item>
        <el-form-item>
          <el-upload ref="upload"
                     action="http://localhost:9090/files/upload"
                     :on-success="filesUploadSuccess"
                     :file-list="data.fileList"
          >
            <el-button type="primary">修改头像</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="data.form.username" disabled/>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="data.form.nickName"/>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="data.form.age"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="data.form.sex" label="男">男</el-radio>
          <el-radio v-model="data.form.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="电话号码" prop="telephone">
          <el-input v-model="data.form.telephone"/>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="update">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>

</style>